package socket.client;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import socket.utils.message.Message;
import socket.utils.message.MsgType;

/**
 * Created by think on 2017/10/30.
 */
public class EchoClientHandler extends SimpleChannelInboundHandler<String>{

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
        Message message = JSON.parseObject(msg+"", Message.class);
        MsgType msgType=message.getType();
        switch (msgType){
            case LOGIN:{
                //向服务器发起登录
                message = new Message(MsgType.LOGIN);
                ctx.writeAndFlush(JSON.toJSONString(message));
            }break;
            case PING:{
                System.out.println("receive ping from server----------");
            }break;
            case SEND:{
                //收到服务端消息
                System.out.println("收到服务端消息："+message.getData());
            }break;
            case NO_TARGET:{
                //收到服务端消息
                System.out.println("找不到targetId:"+message.getTargetId());
            }break;
            default:break;
        }
    }

    /**
     * 利用写空闲发送心跳检测消息
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case WRITER_IDLE:
                    Message pingMsg=new Message(MsgType.PING);
                    ctx.writeAndFlush(JSON.toJSON(pingMsg));
                    System.out.println("send ping to server----------");
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //初始连接当探针到服务端是活跃的时候，发生送一条消息
       // ctx.writeAndFlush(Unpooled.copiedBuffer("有新客户端接入!", CharsetUtil.UTF_8));
        System.out.println("channel is active");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        System.out.println("出现异常！");
    }
}
